# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging
from datetime import datetime, date, timedelta
from urllib import unquote
from urlparse import urlparse

from pylons import tmpl_context as c, session, request
from pylons.i18n import lazy_ugettext as _


from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import in_group

from chowa.lib.base import BaseController, render, Session
from chowa.lib.site.navigation import Tab
from chowa.model.auth import User, Visit
from chowa.model.site import Error

log = logging.getLogger(__name__)

@ControllerProtector(in_group('administrators'))
class ActivityController(BaseController):
    __primary_tabs__ = [
        [
            Tab(params=dict(action='index'),
                caption=_('General')
            ),
            Tab(params=dict(action='users'),
                caption=_('Users')
            ),
            Tab(params=dict(action='visits'),
                caption=_('Visits')
            ),
            Tab(params=dict(action='errors', default__id='all'),
                caption=_('Errors')
            ),
        ]
    ]
    
    __secondary_tabs__ = [
        [
            Tab(params=dict(action='errors', id='all'),
                caption=_('All')
            ),
            Tab(params=dict(action='errors', id='403'),
                caption='Forbidden'
            ),
            Tab(params=dict(action='errors', id='404'),
                caption='Not Found'
            ),
            Tab(params=dict(action='errors', id='500'),
                caption='Internal Server Error'
            ),
        ]
    ]
    
    def index(self):
        c.users = Session.query(User).filter_by(is_online=True).count()
        c.visits = Session.query(Visit).filter_by(date=date.today()).count()
        c.errors = Session.query(Error).filter(Error.happened >= date.today()).count()
        return render('/admin/activity/index.html')
    
    def users(self):
        critical_time = datetime.now() - timedelta(minutes=30)
        c.users = Session.query(User).filter(User.last_activity > critical_time).all()
        return render('/admin/activity/users.html')
    
    def visits(self):
        c.visits = Session.query(Visit).filter_by(date=date.today()).all()
        return render('/admin/activity/visits.html')
    
    def errors(self, id):
        query = Session.query(Error)
        if not id == 'all':
            query = query.filter_by(code=id)
        c.errors = query.filter(Error.happened >= date.today()).all()
        address = request.scheme + '://' + request.host
        c.shrink = lambda u: unquote(u).replace(address, '') if u else ''
        return render('/admin/activity/errors.html')
